iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 68

[Day 65 - 2] Subarray Sum Equals K (Medium)

  • 分享至 

  • xImage
  •  

560. Subarray Sum Equals K

Solution 1: Brute-Force (TLE)

class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        ans = 0
        n = len(nums)
        for i in range(n):
            subSum = 0
            for j in range(i, n):
                subSum += nums[j]
                if subSum == k:
                    ans += 1
        return ans

Time Complexity: O(n^2)
Space Complexity: O(1)

Solution 2: PrefixSum + Hash

from collections import Counter
class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        ans = 0
        prefixSumHistory = Counter({
            0: 1 # Init
        })
        currPrefixSum = 0
        for i in range(len(nums)):
            currPrefixSum += nums[i]
            complementSum = currPrefixSum - k
            if complementSum in prefixSumHistory:
                ans += prefixSumHistory[complementSum]
            prefixSumHistory[currPrefixSum] += 1
        return ans

Time Complexity: O(n)
Space Complexity: O(n)

Reference

https://www.youtube.com/watch?v=mKXIH9GnhgU

Follow-ups

  1. Continuous Subarray Sum

上一篇
[Day 65 - 1] Merge Sorted Array (Easy)
下一篇
[Day 66] Perfect Squares (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言